import React, { useState, useEffect, useCallback } from 'react';
import styles from './index.less';
import './filter.less';
import { useDispatch, useSelector } from 'dva';
import { useHistory } from 'dva';
import moment from 'moment';

import IconWebsite from '../../assets/business-match/icon-website.png';
import IconCheck from '../../assets/business-match/icon-check.png';
import IconUnCheck from '../../assets/business-match/icon-uncheck.png';
import IconHasApply from '../../assets/business-match/apply.png';

import tabs from './tabs';

function Index() {
  const dispatch = useDispatch();
  const history = useHistory();
  const { businessMatchList = [] } = useSelector(({ index }) => index);
  const [tabIndex, setTabIndex] = useState(0);
  const [filterTabIndex, setFilterTabIndex] = useState(0);
  const [dataSource, setDataSource] = useState([]);
  const [filterVisible, setFilterVisible] = useState(false);
  const [checkedList, setCheckedList] = useState([]);
  const [options, setOptions] = useState([]);

  const getList = () => {
    const payload = {};
    dispatch({
      type: 'index/apiGetBusinessMatchList',
      payload,
    });
  };

  const handleFilter = (filterList) => {
    setTabIndex(filterTabIndex);
    setFilterVisible(false);
    if (!filterList.length) {
      return;
    }
    setTimeout(() => {
      const list = businessMatchList.filter(
        (item) =>
          filterList.some((option) => item.demand.indexOf(option) > -1) &&
          moment(item.businessOpportunityMeets[0].startTime).format('YYYY.M.D') ==
            tabs[filterTabIndex].date,
      );
      setDataSource(list);
    }, 100);
  };

  useEffect(() => {
    getList();
  }, []);

  useEffect(() => {
    document.title = 'CHINACYCLE 线上贸易对接会';
  });

  const handleChangeTab = (tab) => {
    setTabIndex(tab.id);
    setCheckedList([]);
  };

  const toApply = (id) => {
    history.push(`/business-match/${id}/${tabs[tabIndex].date}`);
  };

  const toggleOption = (option) => {
    const isExist = checkedList.includes(option);
    let newList = [];
    if (isExist) {
      const idx = checkedList.indexOf(option);
      const newList = [...checkedList];
      newList.splice(idx, 1);
      setCheckedList([...newList]);
    } else {
      newList = [...checkedList];
      newList.push(option);
      setCheckedList(newList);
    }
  };

  const renderOptions = () => {
    const currentTabDataSource = businessMatchList.filter((item) => {
      return (
        item.businessOpportunityMeets &&
        item.businessOpportunityMeets.length &&
        moment(item.businessOpportunityMeets[0].startTime).format('YYYY.M.D') ==
          tabs[filterTabIndex].date
      );
    });
    const options = Array.from(
      new Set(
        currentTabDataSource
          .map((item) => item.demand)
          .map((item) => item.split('、'))
          .flat(1),
      ),
    );
    setOptions(options);
    if (!checkedList.length) {
      setCheckedList(options);
    }
  };

  useEffect(() => {
    setCheckedList([]);
    setTimeout(() => {
      renderOptions();
    }, 100);
  }, [filterTabIndex]);

  useEffect(() => {
    if (businessMatchList.length) {
      const list = [...businessMatchList];
      const currentTabDataSource = list.filter((item) => {
        console.log(moment(item.businessOpportunityMeets[0].startTime).format('YYYY.M.D'));
        return (
          item.businessOpportunityMeets &&
          item.businessOpportunityMeets.length &&
          moment(item.businessOpportunityMeets[0].startTime).format('YYYY.M.D') ==
            tabs[tabIndex].date
        );
      });
      console.log(currentTabDataSource);
      setDataSource(currentTabDataSource);
    }
  }, [tabIndex, businessMatchList]);

  return (
    <div className={styles.page}>
      {filterVisible && (
        <div className="filter-box">
          <div
            className="filter-mask"
            onClick={() => {
              handleFilter(checkedList);
            }}
          ></div>
          <div className="filter-content-box">
            <div className="header">
              <div className="tabs">
                {tabs.map((tab) => (
                  <div
                    className={`tab ${filterTabIndex == tab.id && 'tabActive'}`}
                    onClick={() => {
                      setFilterTabIndex(tab.id);
                      setCheckedList([]);
                    }}
                  >
                    {tab.label}
                  </div>
                ))}
              </div>
              <div className="filterIcon"></div>
            </div>
            <div className="options">
              {options &&
                options.map((option) => (
                  <div className="option">
                    {checkedList.includes(option) ? (
                      <img
                        src={IconCheck}
                        onClick={() => {
                          toggleOption(option);
                        }}
                      />
                    ) : (
                      <img
                        src={IconUnCheck}
                        onClick={() => {
                          toggleOption(option);
                        }}
                      />
                    )}
                    <span>{option}</span>
                  </div>
                ))}
            </div>
            <div className="filter-button-box">
              <div
                className="filter-button"
                onClick={() => {
                  handleFilter(checkedList);
                }}
              >
                选择（{checkedList.length}）
              </div>
            </div>
          </div>
        </div>
      )}
      <div className={styles.header}>
        <div className={styles.tabs}>
          {tabs.map((tab) => (
            <div
              className={`${styles.tab} ${tabIndex == tab.id && styles.tabActive}`}
              onClick={() => handleChangeTab(tab)}
            >
              {tab.label}
            </div>
          ))}
        </div>
        <div
          className={styles.filterIcon}
          onClick={() => {
            renderOptions();
            setFilterTabIndex(tabIndex);
            setFilterVisible(true);
            console.log(checkedList);
          }}
        ></div>
      </div>
      <div className={styles.list}>
        {dataSource.map((item) => (
          <div className={styles.card}>
            <div className={styles.companyName}>{item.companyName}</div>
            <div className={styles.info}>
              <div className={styles.website}>
                <img
                  src={IconWebsite}
                  style={{
                    marginRight: 2,
                  }}
                />
                <span
                  onClick={() => {
                    window.open(`https://${item.website}`);
                  }}
                >
                  {item.website}
                </span>
              </div>
              <div className={styles.country}>{item.countryName}</div>
            </div>
            <div
              className={styles.demand}
              style={{
                marginTop: 12,
                marginBottom: 4,
              }}
            >
              <div
                className={styles.light}
                style={{
                  marginBottom: 5,
                }}
              >
                实际采购需求
              </div>
              <div className={`${styles.dark} ${styles.demandContent}`}>{item.demand}</div>
            </div>
            <div className={styles.footer}>
              <div className={styles.left}>
                <div className={styles.light}>Name</div>
                <div className={`${styles.name} ${styles.dark}`}>{item.name}</div>
                <div className={styles.light}>{item.participant}</div>
              </div>
              <div className={styles.right}>
                {item.businessOpportunityMeets.filter((obj) => obj.reserved).length ==
                item.businessOpportunityMeets.length ? (
                  <div className={styles.hasApply}>
                    {/* <img src={IconHasApply} className={styles.hasApplyIcon} /> */}
                    <span className={styles.hasApplyLabel}>预约已满</span>
                  </div>
                ) : (
                  <div className={`${styles.button}`} onClick={() => toApply(item.id)}>
                    我要申请 {item.businessOpportunityMeets.filter((obj) => obj.reserved).length}/
                    {item.businessOpportunityMeets.length}
                  </div>
                )}
              </div>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

export default Index;
